package com.lishe.lishe.lishe.module.shopingcart.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.lishe.base.common.base.AbstractFragment;
import com.lishe.base.mvp.factory.CreatePresenter;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.bean.AddressBean;
import com.lishe.lishe.lishe.common.Arith;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.event.RefreshAddressEvent;
import com.lishe.lishe.lishe.event.RefreshShopCarCountEvent;
import com.lishe.lishe.lishe.module.excitation.fragment.ExcitationFragment;
import com.lishe.lishe.lishe.module.main.event.TabChangeEvent;
import com.lishe.lishe.lishe.module.mall.view.GoodsAddressDialog;
import com.lishe.lishe.lishe.module.me.activity.AddAddrActivity;
import com.lishe.lishe.lishe.bean.AddressItem;
import com.lishe.lishe.lishe.module.myorder.activity.ConfirmOrderActivity;
import com.lishe.lishe.lishe.module.shopingcart.adapter.ShoppingCarAdapter;
import com.lishe.lishe.lishe.module.shopingcart.bean.ShopCarBean;
import com.lishe.lishe.lishe.module.shopingcart.bean.SubmitOrderBean;
import com.lishe.lishe.lishe.module.shopingcart.presenter.ShopCarPresenter;
import com.lishe.lishe.lishe.module.shopingcart.presenter.ShopCarView;
import com.lishe.lishe.lishe.utils.FormatUtil;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.net.BaseProtocal;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;

/**
 * Bin
 * 购物车
 */
@CreatePresenter(ShopCarPresenter.class)
public class ShopCarFragment extends AbstractFragment<ShopCarView, ShopCarPresenter> implements ShopCarView, View.OnClickListener {

    private Button mBtnSettle;
    private ImageView mCheckAllImg;
    private TextView texReceiveAddress;
    private TextView mTvPrice;
    private ExpandableListView mExpandableListView;
    private SmartRefreshLayout mRefreshLayout;
    private LinearLayout mEmptyLayout;
    private LinearLayout mAddressLayout;
    private LinearLayout mButtomLayout;
    private ShoppingCarAdapter mAdapter;
    private boolean mIsCheckAll = false;
    private List<AddressItem> mAddressList = new ArrayList<>();
    private int mAddressIndex = 0;//地址栏选中标志
    private GoodsAddressDialog mAddressDialog;
    private View rootView;// cache fragment view
    private View mContent;
    private View mErrorLayout;
    private List<ShopCarBean.DataBean> mInfoList = new ArrayList<>();

    private volatile static ShopCarFragment singleton = null;

    public static ShopCarFragment getInstance()   {
        if (singleton == null)  {
            synchronized (ShopCarFragment.class) {
                if (singleton == null)  {
                    singleton= new ShopCarFragment();
                }
            }
        }
        return singleton;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_shopcar, null);
            EventBus.getDefault().register(this);
            mAdapter = new ShoppingCarAdapter(getActivity(), mInfoList);
            mAdapter.setCheckListener(new ShoppingCarAdapter.CheckListener() {
                @Override
                public void onCheck() {
                    EventBus.getDefault().post(new RefreshShopCarCountEvent());
                    mTvPrice.setText("¥" + FormatUtil.numFormat(getPayMoneyAndResetBottomLayout()));
                    if (mInfoList.size() == 0) { //所有商品被删除完后显示空页面
                        showEmpty(true);
                    }
                }
            });
            initView(rootView);
            initListener(rootView);
        }
        return rootView;
    }

    @Override
    public void setMenuVisibility(boolean menuVisible) {
        super.setMenuVisibility(menuVisible);
        if (getView() != null) {
            this.getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
        }
    }

    /**
     * 获取合计金额
     * @return
     */
    public double getPayMoneyAndResetBottomLayout() {
        int selectCount = 0;
        double payMoney = 0;
        boolean isAllSelect = true;

        for (int i = 0; i < mInfoList.size(); i++) {
            for (int j = 0; j < mInfoList.get(i).goodsInfo.size(); j++) {
                if (mInfoList.get(i).goodsInfo.get(j).isCheck) {
                    ShopCarBean.DataBean.GoodsInfoBean bean = mInfoList.get(i).goodsInfo.get(j);
                    double mul = Arith.mul(Double.parseDouble(bean.price), bean.quantity);
                    payMoney = Arith.add(payMoney, mul);
                    selectCount += bean.quantity;
                } else if (isAllSelect) {
                    isAllSelect = false;
                }
            }
        }
        if (selectCount > 0 && mAddressList.size() > 0) {
            mBtnSettle.setBackgroundColor(getResources().getColor(R.color.color_ff4138));
        } else {
            mBtnSettle.setBackgroundColor(getResources().getColor(R.color.gray_9));
        }
        mBtnSettle.setText("去结算(" + selectCount + ")");

        mIsCheckAll = isAllSelect;
        if (mIsCheckAll) {
            mCheckAllImg.setImageResource(R.mipmap.sel_check_icon);
        } else {
            mCheckAllImg.setImageResource(R.mipmap.nor_check_icon);
        }
        return payMoney;
    }

    @Override
    public void onResume() {
        super.onResume();
        getMvpPresenter().getAddressData();
        LoadingUtils.createLoadingDialog(getActivity(), "正在加载", true).show();
        getMvpPresenter().getShopCarData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 初始化
     */
    private void initView(View v) {
        mContent = v.findViewById(R.id.content);
        mErrorLayout = v.findViewById(R.id.error_layout);
        v.findViewById(R.id.error_retry).setOnClickListener(this);

        mBtnSettle = v.findViewById(R.id.settle);
        mCheckAllImg = v.findViewById(R.id.check_img);
        mTvPrice = v.findViewById(R.id.price);
        texReceiveAddress = v.findViewById(R.id.receive_address);

        mExpandableListView = v.findViewById(R.id.expandableListView);
        mExpandableListView.setAdapter(mAdapter);
        mExpandableListView.setGroupIndicator(null);
        mExpandableListView.setDivider(null);
        mExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return true;
            }
        });

        mRefreshLayout = v.findViewById(R.id.refreshlayout);
        mRefreshLayout.setEnableLoadmore(false);
        //购物车为空
        mEmptyLayout = v.findViewById(R.id.empty_layout);
        mButtomLayout = v.findViewById(R.id.buttom_layout);
        mAddressLayout = v.findViewById(R.id.address_layout);

        mButtomLayout.setVisibility(View.GONE);
        mAddressLayout.setVisibility(View.GONE);
    }

    /**
     * 点击事件
     */
    private void initListener(View v) {
        v.findViewById(R.id.goindex).setOnClickListener(this);
        v.findViewById(R.id.check_area).setOnClickListener(this);
        mBtnSettle.setOnClickListener(this);
        texReceiveAddress.setOnClickListener(this);

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getMvpPresenter().getShopCarData();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshAddressEvent event) {
        getMvpPresenter().getAddressData();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.error_retry:
                mErrorLayout.setVisibility(View.GONE);
                break;
            case R.id.goindex://逛逛首页
                EventBus.getDefault().post(new TabChangeEvent(0));
                break;
            case R.id.settle://结算按钮
                if (mAddressList.size() == 0) {
                    ToastUtil.showToast(getActivity(), "请先选择收货地址");
                    return;
                }
                if (!isSelectGoods()) {
                    ToastUtil.showToast(getActivity(), getString(R.string.pls_check_goods));
                    return;
                }
                LoadingUtils.createLoadingDialog(context, "正在生成订单...", false);
                getMvpPresenter().submitOrder(getCartIDs());
                break;
            case R.id.check_area: //全选
                if (mIsCheckAll) {
                    mIsCheckAll = false;
                    mCheckAllImg.setImageResource(R.mipmap.nor_check_icon);
                } else {
                    mIsCheckAll = true;
                    mCheckAllImg.setImageResource(R.mipmap.sel_check_icon);
                }
                mAdapter.checkAll(mIsCheckAll);
                break;
            case R.id.receive_address://地址选择
                if (mAddressList == null || mAddressList.size() == 0) {
                    AddAddrActivity.jumpForResult(getActivity(), Globals.REQUSE_CODE_AddAddrActivity, 1, null);
                    return;
                }

                mAddressDialog = new GoodsAddressDialog(getActivity(), mAddressList, new GoodsAddressDialog.SelectListener() {
                    @Override
                    public void onSelect(int position) {
                        if (position == mAddressIndex) {
                            return;
                        }
                        mAddressIndex = position;
                        LoadingUtils.createLoadingDialog(getActivity(), "正在加载", true).show();
                        getMvpPresenter().modifyDefAddr(mAddressList.get(position).getAddr_id());
                    }

                    @Override
                    public void onNewAddress() {
                        AddAddrActivity.jumpForResult(getActivity(), Globals.REQUSE_CODE_AddAddrActivity, 1, null);
                    }
                });
                mAddressDialog.show();
                break;
        }
    }

    /**
     * 获取选中的各个商品的id
     */
    public ArrayList getCartIDs() {
        ArrayList<String> array = new ArrayList<>();
        for (int i = 0; i < mInfoList.size(); i++) {
            for (int j = 0; j < mInfoList.get(i).goodsInfo.size(); j++) {
                if (mInfoList.get(i).goodsInfo.get(j).isCheck) {
                    array.add(mInfoList.get(i).goodsInfo.get(j).cart_id);
                }
            }
        }
        return array;
    }

    /**
     * 判断是否有选中商品
     */
    private boolean isSelectGoods() {
        for (int i = 0; i < mInfoList.size(); i++) {
            for (int j = 0; j < mInfoList.get(i).goodsInfo.size(); j++) {
                if (mInfoList.get(i).goodsInfo.get(j).isCheck) {
                    return true;
                }
            }
        }
        return false;
    }

    private void showEmpty(boolean isShow) {
        if (isShow) {
            mEmptyLayout.setVisibility(View.VISIBLE);
            mAddressLayout.setVisibility(View.GONE);
            mButtomLayout.setVisibility(View.GONE);
            mRefreshLayout.setVisibility(View.GONE);
        } else {
            mEmptyLayout.setVisibility(View.GONE);
            mAddressLayout.setVisibility(View.VISIBLE);
            mButtomLayout.setVisibility(View.VISIBLE);
            mRefreshLayout.setVisibility(View.VISIBLE);
        }
    }

    public int getDefAddr(List<AddressItem> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getDef_addr() == 1) {
                return i;
            }
        }
        return 0;
    }

    @Override
    public void onLoading() {}

    @Override
    public void onRequestError() {
        mRefreshLayout.finishRefresh();
        ToastUtil.showToast(getActivity(), R.string.network_or_server_exception);
    }

    @Override
    public void onRequestFailure(int errorCode, String msg) {
        if (errorCode == -1 && "购物车为空".equals(msg)) {
            showEmpty(true);
            mAdapter.checkAll(false);
            mContent.setVisibility(View.VISIBLE);
            mRefreshLayout.finishRefresh();
        } else if (errorCode == -1 && "请登录".equals(msg)) {

        } else {
            ToastUtil.showToast(getActivity(), msg);
        }
    }

    @Override
    public void onInitSuccess(ShopCarBean response) {
        if (getActivity() == null) return;
        mInfoList.clear();
        mInfoList.addAll(response.data);
        if (mInfoList.size() != 0) {
            showEmpty(false);
        } else {
            showEmpty(true);
        }
        mAdapter.checkAll(false);
        mAdapter.notifyDataSetChanged();
        mContent.setVisibility(View.VISIBLE);
        mRefreshLayout.finishRefresh();
        expandAllGroup();
    }

    /**
     * 展开所有组
     */
    private void expandAllGroup() {
        for (int i = 0; i < mInfoList.size(); i++) {
            mExpandableListView.expandGroup(i);
        }
    }

    @Override
    public void onAddressSuccess(AddressBean response) {
        mAddressList.clear();
        mAddressList.addAll(response.data);
        if (mAddressList.size() == 0) {
            texReceiveAddress.setText("");
        } else {
            int defPosition = getDefAddr(mAddressList);
            mAddressList.get(defPosition).setCheck(true);
            mAddressIndex = defPosition;
            texReceiveAddress.setText("送至: " + mAddressList.get(defPosition).getArea() + mAddressList.get(defPosition).getAddr());
            if (mAddressDialog != null && mAddressDialog.isShowing()) {
                mAddressDialog.dismiss();
            }
        }
    }

    @Override
    public void onSubmitSuccess(SubmitOrderBean response) {
        ConfirmOrderActivity.jump(getActivity(), response.data);
    }

    @Override
    public void onModifyDefAddrSuccess(BaseProtocal response) {
        //找出选择的地址item 赋值并更新ui
        texReceiveAddress.setText("送至: " + mAddressList.get(mAddressIndex).getArea() + mAddressList.get(mAddressIndex).getAddr());
    }

}